package com.gqh.weather.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinyinUtil {

    public static String getPinYin(String name) {
        if (name == null || name.isEmpty()) {
            return "";
        }

        // 配置拼音输出格式
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE); // 小写
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // 不带声调
        format.setVCharType(HanyuPinyinVCharType.WITH_V); // 用v表示ü

        StringBuilder pinyin = new StringBuilder();

        for (char c : name.toCharArray()) {
            // 判断是否为汉字
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        // 取第一个拼音（多音字取默认的第一个）
                        pinyin.append(pinyinArray[0]);
                    } else {
                        pinyin.append(c);
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    // 如果转换失败，保留原字符
                    pinyin.append(c);
                }
            } else {
                // 非汉字直接追加
                pinyin.append(c);
            }
        }

        return pinyin.toString();
    }
}
